<template>
  <div style="display: flex;text-align: center;justify-content: center">
    <div style="width: 80%;text-align: center;margin-top: 20px" class="card">
      <el-form ref="formRef" :rules="data.rules_person" :model="data.form" label-width="100px"
               style="padding-right: 50px">
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/files/upload/userAvatar"
              :show-file-list="true"
              :list-type="'picture-card'"
              :on-success="handleAvatarSuccess"
          >
            <img v-if='data.form.avatar' :src="data.form.avatar" alt="用户头像" style="width: 100%;"/>
            <el-icon v-else>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="data.form.username" disabled autocomplete="off"/>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="data.form.nickname" autocomplete="off" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="收获地址" prop="address">
          <el-table
              ref="singleTableRef"
              :data="data.tableData"
              highlight-current-row
              max-height="200"
              style="width: 100%"
          >
            <el-table-column type="index" width="40"/>
            <el-table-column property="name" label="收货人" width="100"/>
            <el-table-column property="phone" label="电话号" width="120"/>
            <el-table-column property="address" label="地区" width="120"/>
            <el-table-column property="addressDetail" label="详细地址" width="120"/>
            <el-table-column label="操作" width="160">
              <template #default="scope">
                <el-button type="primary">编辑</el-button>
                <el-button type="danger" @click="deleteAddress(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <div style="justify-content: center;text-align: center;">
          <el-button type="success" @click="data.addVisible=true">新增收获地址</el-button>
          <el-button type="primary" @click="updatePerson">更新我的信息</el-button>
        </div>
      </el-form>
    </div>
    <el-dialog center v-model="data.addVisible" class="card" style="width: 500px" title="确认收货地址并付款">
      <div>
        <el-form :model="data.newAddress" :rules="data.rules_address" ref="formRef" label-width="auto"
                 style="max-width: 600px">
          <el-form-item label="收获人" prop="name">
            <el-input v-model="data.newAddress.name" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="电话号">
            <el-input v-model="data.newAddress.phone" placeholder="请输入电话号"></el-input>
          </el-form-item>
          <el-form-item prop="address" label="地区">
            <el-input v-model="data.newAddress.address" placeholder="请输入地区"></el-input>
          </el-form-item>
          <el-form-item prop="addressDetail" label="详细地址">
            <el-input v-model="data.newAddress.addressDetail" placeholder="请输入详细地址"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.addVisible = false">取消</el-button>
          <el-button type="primary" @click="addAddress">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>
<script setup>

import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import request from "@/utils/request.js";
import {Plus} from "@element-plus/icons-vue";

const formRef = ref()

const data = reactive({
  person: JSON.parse(localStorage.getItem("user_information")),
  form: {},
  rules_address: {
    nickname: [{required: true, message: "请输入昵称", trigger: "blur"}],
    name: [{required: true, message: "请输入收货人名称", trigger: "blur"}],
    phone: [{required: true, message: "请输入电话号", trigger: "blur"}],
    address: [{required: true, message: "请输入地区", trigger: "blur"}],
    addressDetail: [{required: true, message: "请输入详细地址", trigger: "blur"}],
  },
  rules_person: {
    nickname: [{required: true, message: "请输入昵称", trigger: "blur"}],
  },
  tableData: [],
  addVisible: false,
  newAddress: {}

})
const emit = defineEmits(['updatePerson'])
const updatePerson = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/user/update', data.form).then(res => {
        if (res.code === 200) {
          ElMessage.success("更新成功")
          localStorage.setItem("user_information", JSON.stringify(data.form))
          emit('updatePerson')
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
const addAddress = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      data.newAddress.userId = data.person.userId;
      request.post('/address/addAddress', data.newAddress).then(res => {
        if (res.code === 200) {
          console.log(res.code)
          ElMessage.success("地址添加成功！")
          data.addVisible = false
          load()
        } else {
          ElMessage.error("地址添加失败！")
          data.addVisible = false
        }
      })
    }
  })
}
const load = () => {
  console.log(data.person)
  data.person = JSON.parse(localStorage.getItem("user_information"))
  request.get("/address/selectByUserId/" + data.person.userId).then(res => {
    if (res.code === 200) {
      data.tableData = res.data
    } else {
      ElMessage.error(data.msg)
    }
  })

}
const deleteAddress = (row) => {
  console.log(row)
  ElMessageBox.confirm("删除信息后无法恢复，是否确认删除", '删除确认', {type: 'warning'}).then(() => {
    request.delete('/address/deleteAddressById/' + row.addressId).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(data.msg)
      }
    })
  })
}
load()
const handleAvatarSuccess = (res) => {
  console.log(res.data)
  data.form.avatar = res.data;
}
data.form = data.person;
</script>

<!--<style scoped>-->
<!--//.avatar-uploader .avatar {-->
<!--//  width: 128px;-->
<!--//  height: 128px;-->
<!--//  display: block;-->
<!--//}-->
<!--</style>-->

<style>
.avatar-uploader {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
